// function mypromise(){
//    let Promise= new Promise(function (resolve, reject) {
//         const xhr = new window.XMLHttpRequest()
//         let method = options.method.toUpperCase()
//         if (method == 'GET') {
//             let params = changeObjParme(options.data)
//             xhr.open(method, options.url + '?' + params)
//             xhr.send()
//         } else if (method == 'POST') {
//             xhr.open(method, options.url)
//             xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
//             let params = changeObjParme(options.data)
//             xhr.send(params)
//         }

//         xhr.onreadystatechange = function () {
//             if (xhr.readyState == 4) {
//                 if (xhr.status == 200) {
//                     let data = JSON.parse(xhr.responseText)
//                     resolve(data)  // 成功的结果，交给外部回调函数处理
//                 } else {
//                     reject('请求出错')
//                 }
//             }
//         }
//     })
// }
function myPromise(options) {
    //1.创建promise,封装异步任务
    let promise = new Promise(function (resolve, reject) {
        // 2. 封装ajax异步任务
        const xhr = new window.XMLHttpRequest()
        let method = options.method.toUpperCase()
        if (method == 'GET') {
            let params = changeObjParme(options.data)
            xhr.open(method, options.url + '?' + params)
            xhr.send()
        } else if (method == 'POST') {
            xhr.open(method, options.url)
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
            let params = changeObjParme(options.data)
            xhr.send(params)
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    let data = JSON.parse(xhr.responseText)
                    resolve(data) //resolve成功状态
                } else {
                    reject('请求出错 ' + xhr.status) //reject失败状态
                }
            }
        }
    })
    return promise
}
/**
 * 对象转字符串
 * @param {*} obj 
 * @returns 
 */
function changeObjParme(obj) {
    let arr = [] //[username='admin', password=123]
    for (let key in obj) {
        let params = `${key}=${obj[key]}`
        arr.push(params)
    }
    let line = arr.join('&') //username='admin'&password=123

    return line
}
